import { onMounted, ref, watch } from 'vue'
import { useRouter,RouteRecordRaw } from 'vue-router'

import path from "path-browserify"
import Fuse from 'fuse.js'

const fuse = ref()


  /**
 * fuse 实现模糊搜索
 * @param list 需要进行模糊搜索的集合
 */
  const fuseInit = (list: []) => {
    fuse.value = new Fuse(list, {
      shouldSort: true,
      threshold: 0.4,
      location: 0,
      distance: 100,
      minMatchCharLength: 1,
      keys: [
        {
          name: 'title',
          weight: 0.7,
        },
        {
          name: 'path',
          weight: 0.3,
        },
      ],
    })
  }
  /**
   * 筛选出可以在侧边栏显示的路由
   * @param routes 路由
   * @param basePath 路径
   * @param prefixTitle 标题
   */
  const generateRoutes = (routes:RouteRecordRaw[], basePath = '/', prefixTitle = []):any => {
    let filterRoutes = []
    for (const route of routes) {
      // 如果路由已经隐藏，跳过这次
      if (route.meta?.hidden) {
        continue
      }

      const data:any = {
        path: path.resolve(basePath, route.path),
        title: [...prefixTitle],
      }

      // 仅推送有标题的路由
      if (route.meta && route.meta.title) {
          data.title = [...data.title, route.meta.title]

          if (route.redirect !== 'noReDirect') {
          filterRoutes.push(data)
          }
      }

      // 循环子路由
      if (route.children) {
          const childRoutes = generateRoutes(route.children, data.path, data.title)
          if (childRoutes.length >= 1) {
          filterRoutes = [...filterRoutes, ...childRoutes]
          }
      }
    }
    return filterRoutes
  }
//  useSearch 
export function useSearchItem(){
  return {fuseInit, generateRoutes,fuse}
}